//https://qiankun.umijs.org/zh/api
// npm i qiankun -S
// qiankun@2.7.0
/*
*  {
        name:'jpaas-app-portal',//子应用的名称
        entry:'/appPortal/',//访问的路径（子应用必须支持跨域fetch）
        container:'#appPortalHome',//挂载子应用的 dom容器
        activeRule:'/jpaas/appPortalHome/appPortal/',//激活的路径，当我们请求/appPortal的时候 把子应用挂载到 #appPortalHome上去
        props:{//给子应用传固定参数;
            laoyout:false
        }
    }
* */
import {I18Parse} from "@lowcode/jpaas-common-lib";
import miniFrontLang from '../../locales/lang/impl/layouts/miniFrontLang';
let lang = miniFrontLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.miniFrontLang.msgTips,langKey, text)
}

import {addGlobalUncaughtErrorHandler, initGlobalState, registerMicroApps, start} from "qiankun";
import store from "@/store";
import {mapMutations, mapState} from "vuex";
import {getParentPath} from "@/utils/routerUtil";
import { cloneDeep } from 'lodash-es';
let addMiniFront = (vueApp,self)=>{
    //在这里注册并启动 qiankun
    const subApp = vueApp ;
    let subAppArr = subApp.map(item=>{
        return item.name ;
    })
    //注册乾坤路由；
    registerMicroApps(subApp,{
        beforeLoad(app){
            if(subAppArr.includes(app.name)){
                store.commit('appSetting/setOpenFrontLoading',true);
                window.Vue2 = window.Vue;
                window.Vue = undefined;
            }else {
                if(window.Vue2){
                    window.Vue = window.Vue2;
                    window.Vue2 = undefined;
                }
            }
        },
        beforeMount(app){//微前端加载完成
            store.commit('appSetting/setOpenFrontLoading',false);
            console.log(i18n('definedButtons','用户自定义按钮'))
        },
        beforeUnmount(app){
            if(window.Vue2){
                window.Vue = window.Vue2;
                window.Vue2 = undefined;
            }
        },
        afterMount(){},
        afterUnmount(){}
    });
    addGlobalUncaughtErrorHandler((event) => {
        const { message: msg } = event
        if (msg && msg.includes("died in status LOADING_SOURCE_CODE")) {
            self.tipsMessage();
        }
    })
}
export default {
    computed: {
        ...mapState({
            navigation: state => state.appSetting.navigation
        })
    },
    mounted() {
        if (!window.qiankunStarted) {
            window.qiankunStarted = true;
            /*
            * {
                prefetch:false//取消预加载
            }
            * */
            start(
                {
                    prefetch:false//取消预加载
                }
            );
        }
    },
    methods:{
        ...mapMutations('appSetting', ['setNavigation','setActiveFront','setAppKey','setSelecteKeys','setActiveKey','setOpenFront']),
        tipsMessage:_.debounce(function (){
            this.$message.warning(i18n('microApplication','微应用加载失败，请检查应用是否可运行'));
        },500),
        innnerFrontOpen(obj,path,menu,open){
            if(!menu){ return }
            if(obj.clientCode){
                obj.key = obj.clientCode ;
                obj.title = obj.clientName ;
            }
            let _key = obj.key;
            this.leftMenu = obj;
            //设置选择的微前端数据
            this.setSelectFrontData(obj,menu);
            //设置顶部menu选中
            this.setAppKey(_key);
            this.setSelecteKeys([menu.key]);
            this.setActiveKey(menu.key);
            //打开状态
            this.setOpenFront(true);
            let _path = {path: '/appPortalHome/'+ _key +'Portal/' };
            if(path){
                _path = {path: '/appPortalHome/'+ _key +'Portal' + path};
            }
            let _open = open ? open : false;
            store.commit('appSetting/setOpenFrontLoading',_open);
            debugger
            this.$router.push(_path);
        },
        setSelectFrontData(obj,menu){//设置选择的微前端数据
            sessionStorage.setItem('CUR_APP_ID',obj.appId);
            let _activeFrontData = {//设置选择的微前端
                title:obj.title,
                backColor: obj.backColor,
                icon:obj.icon,
                appId:obj.appId
            }
            this.setActiveFront(_activeFrontData);
            let isSelect = this.navigation.admin.findIndex(item=>{return item.key == menu.key});
            let nav = cloneDeep(this.navigation);
            if(isSelect > -1){
                nav.admin.splice(isSelect,1,menu);
                this.setNavigation({...nav})
            }else {
                nav.admin = [...nav.admin,menu]
                this.setNavigation(nav)
            }
            let state = {data:menu}
            const actions = initGlobalState({});
            actions.setGlobalState(state);
        },
        openFirstFront(item){//获取微前端第一个菜单；
            if(!item.children){return item}
            let getFirstMenu = (arr) => {
                let firstMenu = arr[0];
                if(!firstMenu.children){
                    return firstMenu ;
                }else
                if(firstMenu.children && firstMenu.children.length > 0){
                    return  getFirstMenu(firstMenu.children);
                }
            }
            //获取第一个菜单；
            let menu = getFirstMenu(item.children);
            let _parent = this.$router.options.routes.find(parent=>{
                return parent.id == menu.appId ;
            })
            let parentMenuArr = getParentPath([_parent], menu.id);
            let firstPath = parentMenuArr.reverse().map(obj=>{
                return obj.path ;
            }).join('/')
            return {firstPath:firstPath,firstMenu:menu} ;
        }
    },
    watch: {
        menus:{
            handler:function (v,ov){
                let data = v ;
                if(!data || data.length == 0){ return }
                //menuNavType :0内置 , 1外部打开,2内置打开
                let arr = []
                let baseURL = process.env.VUE_APP_PORTAL_PATH;
                data.forEach(item=>{
                    if(["2"].includes(item.menuNavType)){
                        let path = baseURL +'/'+ item.key +'Portal/';
                        let hasOwn = arr.find(obj=>{return obj.name == item.key + '-portal'});
                        if(!hasOwn){
                            arr.push({
                                name: item.key+'-portal',//子应用的名称
                                entry:item.appPath +"/",//访问的路径,默认为子应用的nginx配置（子应用必须支持跨域fetch）
                                container:'#appPortalHome',//挂载子应用的 dom容器
                                activeRule:path,//激活的路径，当我们请求/vue1的时候 把子应用挂载到 #vue1App上去
                                loader:(loading)=>{
                                    console.log('我触发了')
                                   // store.commit('appSetting/setOpenFrontLoading',loading);
                                },//加载状态
                                props:{
                                    data:item,
                                    baseUrl:path,
                                }
                            })
                        }
                    }
                })
                addMiniFront(arr,this);
            },
            deep:true,
            immediate:true
        }
    }
}